package com.jumi.microservice.controller.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jm.member.common.core.exception.BaseException;
import com.jm.member.common.core.utils.ServletUtils;
import com.jm.member.common.jwt.constant.JwtAdminInfo;
import com.jm.member.common.jwt.util.JwtTokenUtil;
import com.jm.member.common.redis.service.RedisService;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.dto.order.OrderInfoRequest;
import com.jumi.microservice.dto.order.OrderResponse;
import com.jumi.microservice.dto.order.UserOrderRequest;
import com.jumi.microservice.dto.reponse.GoldPromoterReviewReponse;
import com.jumi.microservice.dto.reponse.JmUserReponse;
import com.jumi.microservice.dto.reponse.api.UserIndexResponse;
import com.jumi.microservice.dto.request.UserInfoUpdateRequest;
import com.jumi.microservice.entity.*;
import com.jumi.microservice.entity.vo.JmUserSetVo;
import com.jumi.microservice.enums.CheckStatus;
import com.jumi.microservice.enums.CommonEnum;
import com.jumi.microservice.enums.FenXiaoStatus;
import com.jumi.microservice.enums.MessageType;
import com.jumi.microservice.service.*;
import com.jumi.microservice.util.MessageUtil;
import com.jumi.microservice.util.PasswordUtils;
import com.jumi.microservice.util.WrapperUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/api/userinfo")
@Api(value = "C-个人信息", tags = "C-个人信息接口")
public class JmUserInfoController {


    @Autowired
    IJmUserService userService;


    @Autowired
    IJmAreaService jmAreaService;

    @DubboReference(check = false)
    IOrderService orderService;

    @Autowired
    RedisService redisService;

    @Autowired
    IJmRealnameAuthenticationService realNameService;

    @Autowired
    IJmIdentityAuthenticationService identityAuthenticationService;


    @Resource
    IJmJpushUserService jpushUserService;

    @DubboReference(check = false)
    IWalletInOrOutService iWalletInOrOutService;

    @GetMapping("/userSet")
    @ApiOperation(value = "用户个人设置")
    public ResponseResult<JmUserSetVo> userSet() {
        Integer memberId = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        JmUserSetVo vo = userService.findUserSetById(memberId);
        return ResponseResult.success(vo);
    }

    @PostMapping("/switchJpush")
    @ApiImplicitParam(name = "jpushStatus", value = "极光推送状态值;0=关闭,1=开启", required = true)
    public ResponseResult switchJpush(Integer jpushStatus) {
        if (jpushStatus == null)
            return ResponseResult.error("状态值不能为空!");
        else if (jpushStatus != 0 && jpushStatus != 1)
            return ResponseResult.error("状态值不合法!");
        Integer memberId = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        String registerId = ServletUtils.getStrHeader(JwtAdminInfo.jpushRegisterId);
        UpdateWrapper<JmJpushUser> wrapper = new UpdateWrapper<>();
        wrapper.set("status", jpushStatus);
        wrapper.eq("uid", memberId);
        wrapper.eq("register_id", registerId);
        jpushUserService.update(wrapper);
        return ResponseResult.success("操作成功");
    }

    @GetMapping("/userOption")
    @ApiOperation(value = "用户个人设置")
    public ResponseResult<UserIndexResponse> userCenter() {
        Integer memberId = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
//        Integer memberId = 222;
        StringBuffer msg = new StringBuffer();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("id", memberId);
        Page page = userService.getPage(new Page(1, 1), wrapper);
        List<JmUserReponse> records = page.getRecords();
        JmUserReponse jmUserReponse = new JmUserReponse();
        if (records.size() > 0) {
            jmUserReponse = records.get(0);
            setCheckStatus(memberId, jmUserReponse);
        }

        //获取实名认证姓名
        QueryWrapper Realwrapper = new QueryWrapper();
        Realwrapper.eq("uid", memberId);
        JmRealnameAuthentication Realpage = realNameService.getOne(Realwrapper);
        if (ObjectUtil.isNotEmpty(Realpage)) {
            jmUserReponse.setRealName(Realpage.getTruename());
        }
        // 获取优惠额度
        JmExtraDiscount discount = extraDiscountService.getDiscountByUid(memberId);
        if (ObjectUtil.isNotEmpty(discount)) {
            jmUserReponse.setDiscount(discount.getDiscount());
        }
        UserIndexResponse userIndexResponse = new UserIndexResponse();
        BeanUtil.copyProperties(jmUserReponse, userIndexResponse);
        userIndexResponse = this.fillObject(userIndexResponse, memberId, msg);
        try {
            BigDecimal availablePredeposit = iWalletInOrOutService.waitCash(memberId.longValue());
            userIndexResponse.setAvailablePredeposit(availablePredeposit);
        } catch (Exception e) {
            msg.append("钱包调用服务失败,可提现收益异常!");
        }
        if (msg.length() == 0)
            msg.append("操作成功!");
        return ResponseResult.success(msg.toString(), userIndexResponse);
    }

    @Autowired
    IJmUserFenxiaoService fenxiaoService;

    private UserIndexResponse fillObject(UserIndexResponse userIndexResponse, Integer memberId, StringBuffer msg) {
        Integer commentNum = 0, orderReadyPay = 0, orderReadyShip = 0, orderReadyReceive = 0;
        try {

            UserOrderRequest param = new UserOrderRequest();
            param.setUid(memberId);
            Byte orderStatus = 1;
            param.setOrderStatus(orderStatus);
            orderReadyPay = orderService.countUserOrder(param);
            orderStatus = 2;
            param.setOrderStatus(orderStatus);
            orderReadyShip = orderService.countUserOrder(param);
            orderStatus = 3;
            param.setOrderStatus(orderStatus);
            orderReadyReceive = orderService.countUserOrder(param);

            commentNum = orderService.waitCommentCount(memberId.longValue());
        } catch (Exception e) {
            msg.append("订单服务调用异常!");
        }

        userIndexResponse.setCommentNum(commentNum);
        userIndexResponse.setOrderReadyPay(orderReadyPay);
        userIndexResponse.setOrderReadyShip(orderReadyShip);
        userIndexResponse.setOrderReadyReceive(orderReadyReceive);

        return userIndexResponse;
    }

    @GetMapping("/index")
    @ApiOperation(value = "用户个人首页信息")
    public ResponseResult<UserIndexResponse> index() {
        Integer memberId = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);   //Integer.parseInt(ServletUtils.getRequest().getHeader("apiUserId"));
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.select("id,name,truename", "avatar", "level", "available_predeposit");
        wrapper.eq("id", memberId);
        JmUser one = userService.getOne(wrapper);
        if (ObjectUtil.isEmpty(one)) {
            return ResponseResult.error("未查询到用户信息!");
        }
        UserIndexResponse userInfoResponse = new UserIndexResponse();
        BeanUtils.copyProperties(one, userInfoResponse);
        //0=已取消，1=代付款，2=代发货，3=待收货，4=已完成
        OrderInfoRequest orderInfoRequest = new OrderInfoRequest();
        orderInfoRequest.setUid(memberId.longValue());
        //用户的订单信息
        List<OrderResponse> orderInfo = new ArrayList<>();
        //用户待评价数量

        /*for (OrderResponse orderResponse : orderInfo) {
            Byte orderStatus = orderResponse.getOrderStatus();
            if (orderStatus == 1) {
                int orderReadyPay = userInfoResponse.getOrderReadyPay() + 1;
                userInfoResponse.setOrderReadyPay(orderReadyPay);
            } else if (orderStatus == 2) {
                int orderReadyShip = userInfoResponse.getOrderReadyShip() + 1;
                userInfoResponse.setOrderReadyShip(orderReadyShip);
            } else if (orderStatus == 3) {
                int orderReadyReceive = userInfoResponse.getOrderReadyReceive() + 1;
                userInfoResponse.setOrderReadyReceive(orderReadyReceive);
            }
        }*/



        StringBuffer msg = new StringBuffer();
        userInfoResponse = this.fillObject(userInfoResponse, memberId, msg);
        setCheckStatus(memberId, userInfoResponse);
        //获取总收益
        JmUserFenxiao fenxiao = new JmUserFenxiao();
        fenxiao.setIsDel(CommonEnum.否);
        fenxiao.setUid(memberId);
        wrapper = WrapperUtil.getWrapper(null, fenxiao);
        wrapper.ne("status", FenXiaoStatus.失效);
        BigDecimal sumYongJin = fenxiaoService.getSumYongJin(wrapper);
        userInfoResponse.setPerformance(sumYongJin);
        //---
        //获取优惠信息
        JmExtraDiscount discount = extraDiscountService.getDiscountByUid(memberId);
        if (ObjectUtil.isNotEmpty(discount)) {
            userInfoResponse.setDiscount(discount.getDiscount());
        }
        if (msg.length() == 0)
            msg.append("操作成功!");
        return ResponseResult.success(msg.toString(), userInfoResponse);
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改个人信息")
    public ResponseResult update(UserInfoUpdateRequest userInfoUpdateRequest) {

        Integer memberId = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        JmUser user = new JmUser();
        BeanUtil.copyProperties(userInfoUpdateRequest, user);
        user.setUpdateTime(LocalDateTime.now());
        user.setId(memberId);
        boolean result = userService.updateById(user);
        if (result) return ResponseResult.success("修改成功");
        return ResponseResult.error("修改失败");

    }

    @PostMapping("/set_pay_pwd")
    @ApiOperation(value = "设置支付密码")
    public ResponseResult setPayPwd(@ApiParam(required = true, value = "支付密码") @RequestParam String payPwd,
                                    @ApiParam(required = true, value = "确认支付密码") @RequestParam String againPayPwd) {
        Integer memberId = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        if (!payPwd.equals(againPayPwd)) return ResponseResult.error("两次输入密码不一致,请重新输入");
        String password = PasswordUtils.passwd(payPwd);
        JmUser jmUser = new JmUser();
        jmUser.setId(memberId);
        jmUser.setPaypwd(password);
        boolean result = userService.updateById(jmUser);
        if (result) return ResponseResult.success();
        return ResponseResult.error();

    }


    @PostMapping("/editMobile")
    @ApiOperation(value = "修改手机号")
    public ResponseResult editMobile(@ApiParam(required = true, value = "手机号") @RequestParam String mobile,
                                     @ApiParam(required = true, value = "验证码") @RequestParam String code) {
        Integer memberId = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        //校验验证码
        MessageUtil.checkCode(code, redisService, MessageType.修改手机号.getValue() + mobile);
        if (checkMobileExist(mobile)) {
            return ResponseResult.error("该手机号已被注册过");
        }
        JmUser jmUser = new JmUser();
        jmUser.setId(memberId);
        jmUser.setMobile(mobile);
        boolean result = userService.updateById(jmUser);
        if (result) return ResponseResult.success();
        return ResponseResult.error();

    }

    public boolean checkMobileExist(String mobile) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("mobile", mobile);
        JmUser jmUser = userService.getOne(wrapper);
        if (ObjectUtil.isNotEmpty(jmUser)) return true;
        return false;

    }

    @PostMapping("/setloginpwd")
    @ApiOperation(value = "设置登录密码")
    public ResponseResult setLoginPwd(@ApiParam(required = true, value = "手机号") @RequestParam String mobile,
                                      @ApiParam(required = true, value = "验证码") @RequestParam String code,
                                      @ApiParam(required = true, value = "发送类型") @RequestParam String pwd
    ) {
        Integer memberId = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        //手机验证码校验
        MessageUtil.checkCode(code, redisService, MessageType.设置密码验证.getValue() + mobile);
        String password = PasswordUtils.passwd(pwd);
        JmUser jmUser = new JmUser();
        jmUser.setId(memberId);
        jmUser.setPasswd(password);
        String pattern = JwtTokenUtil.prefix + memberId + "-*";
        Collection<String> keys = redisService.keys(pattern);
        redisService.deleteObject(keys);
        boolean result = userService.updateById(jmUser);
        if (result) return ResponseResult.success();
        return ResponseResult.error();
    }

    @Autowired
    IJmGoldPromoterReviewService goldPromoterReviewService;
    @Autowired
    IJmExtraDiscountService extraDiscountService;

    /**
     * 获取用户的实名认证 和 店长认证状态
     *
     * @param memberId
     */
    public void setCheckStatus(Integer memberId, JmUserReponse jmUserReponse) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("uid", memberId);
        JmRealnameAuthentication realNameServiceOne = realNameService.getOne(wrapper);
        if (ObjectUtil.isNotEmpty(realNameServiceOne)) {
            jmUserReponse.setIsRealnameAuthentication(realNameServiceOne.getStatus().getValue());
        } else {
            jmUserReponse.setIsRealnameAuthentication(CheckStatus.未申请.getValue());
        }
        JmIdentityAuthentication one = identityAuthenticationService.getOne(wrapper);
        if (ObjectUtil.isNotEmpty(one)) {
            jmUserReponse.setIsIdentityAuthentication(one.getStatus().getValue());
        } else {
            jmUserReponse.setIsIdentityAuthentication(CheckStatus.未申请.getValue());
        }
        GoldPromoterReviewReponse goldInfoById = goldPromoterReviewService.getGoldInfoById(memberId);
        if (ObjectUtil.isNotEmpty(goldInfoById)) {
            jmUserReponse.setGoldCheckStatus(goldInfoById.getStatus().getValue());
        } else {
            jmUserReponse.setGoldCheckStatus(CheckStatus.未申请.getValue());
        }
    }

    @PostMapping("/deleteWeiXin")
    @ApiOperation(value = "解绑微信")
    public ResponseResult deleteWeiXin() {
        Integer memberId = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("id", memberId);
        JmUser jmUser = userService.getOne(wrapper);

        jmUser.setWxOpenid("");
        jmUser.setWeixinUnionid("");
        boolean result = userService.updateById(jmUser);
        if (result) return ResponseResult.success();
        return ResponseResult.error();

    }


}
